//
//  cellView.swift
//  MichaelToy
//
//  Created by MichaelSun on 2017/11/3.
//  Copyright © 2017年 MichaelSun. All rights reserved.
//

import UIKit
@IBDesignable
class cellView: UIView, UITextFieldDelegate  {

    @IBOutlet var backView: UIView!
    @IBOutlet weak var nameLble: UILabel!
    @IBOutlet weak var slider: UISlider!
    @IBOutlet weak var valueField: UITextField!
    @IBInspectable var title = ""
    var value: Float {
        set {
            var usedValue = newValue
            if usedValue < 0 {
                usedValue = 0
            }else if usedValue > 1{
                usedValue = 1
            }
            valueField.text = String(Int(usedValue * 255))
            slider.value = usedValue
            slider.thumbTintColor = UIColor(white: CGFloat(usedValue), alpha: 1)
        }
        get {
            return slider.value
        }
        
    }
    
    
    override func awakeFromNib() {
        Bundle.main.loadNibNamed("cellView", owner: self, options: nil)
        self.backView.frame = self.bounds
        self.addSubview(self.backView)
        self.backgroundColor = UIColor.clear
        valueField.delegate = self
        value = 0.5
        nameLble.text = title
    }
    @IBAction func sliderValueChanged(_ sender: Any) {
       value = slider.value
    }
    func textField(_ textField: UITextField, shouldChangeCharactersIn range: NSRange, replacementString string: String) -> Bool {
        let newNSString = NSString(string: textField.text!)
        let newString = newNSString.replacingCharacters(in: range, with: string)
        let intValue =  Int(newString)
        if intValue != nil{
            value =  Float(intValue!) / 255.0
           
        }else{
            print(newString, newString.count)
            if newString.count == 0 {
                value = 0
            }
              
            
        }
        return false
       
    }

    
   

}
